#include <8052.h>
#include <stdlib.h>
#include <stdio.h>
#include "lcd1602.h"
#include "time_show_in_led1602.h"

#define FOSC 11059200L //晶振时钟

//时间结构体
struct TIME_STRUCT
{
    char Hour;
    char Minute;
    char Second;
} CurrTime = {0, 0, 0};

//定时器低位与高位
char TIMER_TL_DATA, TIMER_TH_DATA;
//定时器中断次数
char TIMER_COUNT = 0;

char Flag = 0;

//自己写个int转char（只转最后一位）
char itoc(int i)
{
    return i % 10 + 48;
}

void show_time_in_lcd1062()
{
    //给TL&TH赋值，除以20是50ms，以最小的中断次数减少中断代码带来的误差（不能再小于20了，因为8位最多65536）
    unsigned int t1ms = (65536 - (FOSC / 12 / 20)); //=65536-46080
    TIMER_TL_DATA = (unsigned char)t1ms;
    t1ms = t1ms >> 8;
    TIMER_TH_DATA = (unsigned char)t1ms;

    //开中断
    TMOD = 0x01;         //开启一个定时器
    TL0 = TIMER_TL_DATA; //reload timer0 low byte
    TH0 = TIMER_TH_DATA; //reload timer0 high byte
    TR0 = 1;             //timer0 start running
    ET0 = 1;             //enable timer0 interrupt
    EA = 1;              //open global interrupt switch

    //重置段选位选
    P2_6 = P2_7 = 0;

    P3_4 = 0;
    write_cmd(0b00111000); //显示模式设置
    write_cmd(0b00001100); //显示开，无光标闪烁
    //write_cmd(0b00000110); //整屏左移
    write_cmd(0x01); //清屏

    char curr = Flag;
    while (1)
    {
        if (curr != Flag)
        {
            curr = Flag;
            //写入位置，第一排第2格
            int addr = 0x80 + 4;
            write_cmd(addr); //指针，第一行
            write_data(itoc(CurrTime.Hour / 10));
            write_data(itoc(CurrTime.Hour % 10));
            write_data(curr ? ':' : ' ');
            write_data(itoc(CurrTime.Minute / 10));
            write_data(itoc(CurrTime.Minute % 10));
            write_data(curr ? ':' : ' ');
            write_data(itoc(CurrTime.Second / 10));
            write_data(itoc(CurrTime.Second % 10));
        }
    }
}

//定时器0 //用于显示数码管
void timer_show_in_led_interrupt1(void) __interrupt 1
{
    //重新赋值再来
    TL0 = TIMER_TL_DATA;
    TH0 = TIMER_TH_DATA;
    TIMER_COUNT++;
    if (TIMER_COUNT == 20)
    { //跑完1000ms  10ms X 100 = 1000ms = 1s
        TIMER_COUNT = 0;
        Flag = Flag ? 0 : 1;
        CurrTime.Second++;
        if (CurrTime.Second >= 60)
        {
            CurrTime.Second = 0;
            CurrTime.Minute++;
        }
        if (CurrTime.Minute >= 60)
        {
            CurrTime.Minute = 0;
            CurrTime.Hour++;
        }
        if (CurrTime.Hour >= 24)
        {
            CurrTime.Hour = 0;
        }
    }
}